package exogwt.server.util;

import org.exoplatform.container.*;
import org.exoplatform.container.client.ClientInfo;
import org.exoplatform.services.jcr.RepositoryService;
import org.exoplatform.services.jcr.config.RepositoryConfigurationException;
import org.picocontainer.alternatives.AbstractDelegatingMutablePicoContainer;

import javax.jcr.Session;
import javax.jcr.Repository;
import javax.jcr.RepositoryException;

/**
 * Miscellaneous utility methods for exo platform integration.
 *
 * @author Andriy Zhdanov
 */
public final class Exo {
    // hide constructor
    private Exo() {

    }

    /**
     * Gets component form Pico container.
     *
     * @param componentClass interface.
     * @return component.
     */
    public static Object getComponent(Class componentClass) {
        return getExoContainer().getComponentInstanceOfType(componentClass);

    }

    /**
     * Gets container.
     *
     * @return container.
     */
    public static ExoContainer getExoContainer() {
        return ExoContainerContext.getCurrentContainer();
    }

    /**
     * Gets session container by id.
     *
     * @param id http session id.
     * @return session container if it is available.
     */
    public static SessionContainer getSessionContainer(String id) {
        SessionManagerContainer sessionManagerContainer =
                (SessionManagerContainer) getExoContainer();
        SessionManager sessionManager = sessionManagerContainer.getSessionManager();
        return sessionManager.getSessionContainer(id);
    }

    /**
     * Creates and initializes session container.
     *
     * @param id session container id.
     * @param clientInfo client information.
     * @return session container.
     */
    public static SessionContainer createSessionContainer(String id,
            ClientInfo clientInfo) {
        SessionManagerContainer sessionManagerContainer =
                (SessionManagerContainer) getExoContainer();
        SessionContainer sessionContainer =
                sessionManagerContainer.createSessionContainer(
                        id, "default");
        sessionContainer.setClientInfo(clientInfo);
        return sessionContainer;
    }

    public static Session getSession() throws RepositoryConfigurationException, RepositoryException {
        SessionContainer sessionContainer = SessionContainer.getInstance();
        Session session = (Session) sessionContainer.get("exogwt.jcr.session");
        if (session == null || !session.isLive()) {
            RepositoryService repositoryService = (RepositoryService) getComponent(
                    RepositoryService.class);
            Repository jcrRepository = repositoryService.getRepository();
            session = jcrRepository.login();
            sessionContainer.put("exogwt.jcr.session", session);
        }
        return session;
    }
}
